package com.bittech.chatroom.web.api;

import com.bittech.chatroom.service.UserAccountService;
import com.bittech.chatroom.util.CommUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: yuisama
 * @Date: 2019-06-25 16:29
 * @Description:
 */
@WebServlet(urlPatterns = "/doRegister")
public class UserRegHandlerServlet extends HttpServlet {
    private UserAccountService userAccountService = new UserAccountService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out = null;
        resp.setContentType("text/html;charset=utf-8");
        out = resp.getWriter();
        // 获取表单提交的用户名与密码
        String userName = req.getParameter("username");
        String password = req.getParameter("password");
        if (CommUtils.strIsEmpty(userName) || CommUtils.strIsEmpty(password)) {
            //用户名或密码为空
            out.print("<script language=\"javascript\">alert('用户名或密码为空，请查证后再次重试!');</script>");
            resp.sendRedirect("/tryRegistration");
        }
        if (userAccountService.userReg(userName,password)) {
            //注册成功，重定向登录页面
            out.print("<script language=\"javascript\">alert('注册成功，欢迎使用!'); " +
                    "window.location.href=\"/index\";" +
                    "</script>");
        }else {
            //注册失败重定向注册页面
            out.print("<script language=\"javascript\">alert('用户名重复，请更换名称再试!');" +
                    "window.location.href=\"/tryRegistration\";" +
                    "</script>");
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
